#include "playwavthread.h"
#include <SDL2/SDL.h>
#include <QFile>

struct PullData{

    Uint8* data;
    Uint32 len;
    int sendLen;

    PullData() {

        data = nullptr;
        len = 0;
        sendLen = 0;
    }
};

PlayWAVThread::PlayWAVThread(QObject *parent) : QThread(parent)
{

    init();
}

PlayWAVThread::~PlayWAVThread()
{

    disconnect();

    requestInterruption();

    quit();

    wait();

    qDebug() << "PlayWAVThread destroy";
}

void PlayWAVThread::init()
{
    connect(this,&QThread::finished,this,&QThread::deleteLater);
}


void pullDataCallBack(void *userdata,
              Uint8 * stream,
               int len){

    memset(stream,0,len);

    PullData* pullData = (PullData*)userdata;
    if(pullData == nullptr ||  pullData->len <= 0) {

        return;
    }

    pullData->sendLen = len > pullData->len ? pullData->len:len;
    SDL_MixAudio(stream,pullData->data,pullData->sendLen,SDL_MIX_MAXVOLUME);

    pullData->data += pullData->sendLen;
    pullData->len -= pullData->sendLen;
}

void PlayWAVThread::run()
{

    int res = SDL_Init(SDL_INIT_AUDIO);

    if(res != 0) {

      qDebug() << "SDL_Init fail";
      return;
    }

    const char* wavFilePath = "/Users/apple/Documents/ffmpeg/qt/audio/recoding_01.wav";
    SDL_AudioSpec spec;
    /**
    * @brief SDL_LoadWAV
    *
    * extern DECLSPEC SDL_AudioSpec *SDLCALL SDL_LoadWAV_RW(SDL_RWops * src,
                                                      int freesrc,
                                                      SDL_AudioSpec * spec,
                                                      Uint8 ** audio_buf,
                                                      Uint32 * audio_len);
    #define SDL_LoadWAV(file, spec, audio_buf, audio_len) \
    SDL_LoadWAV_RW(SDL_RWFromFile(file, "rb"),1, spec,audio_buf,audio_len)
    */

    Uint8* audio_data = nullptr;
    Uint32 audio_data_len = 0;
    SDL_AudioSpec * audioSpec = SDL_LoadWAV(wavFilePath,&spec,&audio_data,&audio_data_len);

    if(audioSpec ==nullptr) {

        qDebug() << "SDL_LoadWAV fail";
        SDL_Quit();
        return;
    }


    audioSpec->samples = 1024;
    audioSpec->callback = pullDataCallBack;

    PullData pullData;
    pullData.data = audio_data;
    pullData.len = audio_data_len;
    audioSpec->userdata = &pullData;


    if (SDL_OpenAudio(audioSpec,nullptr)){

        qDebug() << "SDL_OpenAudio fail";
        SDL_FreeWAV(audio_data);
        SDL_Quit();
        return;
    }

    SDL_PauseAudio(0);

    int bytesPerSample = audioSpec->freq * audioSpec->channels * (SDL_AUDIO_BITSIZE(audioSpec->format) >> 3);
    while (!isInterruptionRequested()) {

        if(pullData.len > 0) {

            continue;
        }

        unsigned long long time = 1000.0 * pullData.sendLen / bytesPerSample;
        qDebug() << "delay time:" << time;
        SDL_Delay(time);
        break;
    }

    SDL_FreeWAV(audio_data);
    SDL_CloseAudio();
    SDL_Quit();
}
